package controls.challengeHistory {
	
	import mx.collections.XMLListCollection;
	import mx.containers.Panel;
	import mx.controls.Alert;
	import mx.events.FlexEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	
	/**
	 * @author Brent Kersanske
	 */ 
	public class ChallengeHistoryDatagridClass extends Panel {
		
		[Bindable]
		public var challenges:XMLListCollection;
		
		[Bindable]
		public var challengeHistoryTitle:String;
	
		[Bindable]
		public var challengeService:HTTPService;		
		
		private var _challengesFilePath:String;
		
		/**
		 * Constructor for the challenge history data grid.
		 */ 
		public function ChallengeHistoryDatagridClass() {
			addEventListener(FlexEvent.CREATION_COMPLETE, handleCreationComplete);
		}
		
		[Bindable]
		public function set challengesFilePath(newFilePath:String):void {
			_challengesFilePath = newFilePath;
			this.challengeHistoryTitle = "";
			challenges.removeAll();
			updateChallenges();
		}
		
		public function get challengesFilePath():String {
			return _challengesFilePath;
		}
		
		private function handleCreationComplete(e:FlexEvent):void {
			init();
		}
				
		private function init():void {   
			this.challenges = new XMLListCollection();
        }
       
        private function updateChallenges():void {
        	this.challengeService.url = this.challengesFilePath;
        	this.challengeService.send(); 
        }
       
		/**
		 * 
		 */ 		
		public function handleHTTPServiceFault(event:FaultEvent):void {
			Alert.show(event.fault.faultString);			
		}
		
		/**
		 * 
		 */ 
		public function handleChallengesResult(event:ResultEvent):void {
			var xmlList:XMLList 	   = XML(event.result).challenge;
            challenges				   = new XMLListCollection(xmlList);
            this.challengeHistoryTitle = "Accepted Challenges (" + challenges.length + ") total";
		}
	}
}